package com.mongodb.controller;

import com.mongodb.pojo.GroupEntity;
import com.mongodb.pojo.UserPojo;
import com.mongodb.repository.UserRepository;
import com.mongodb.util.MongoUtil;
import com.mongodb.vo.UserPojoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.LookupOperation;
import org.springframework.data.mongodb.core.aggregation.SortOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author xiaochi
 * @date 2022/3/17 10:22
 * @desc TestController
 */
@RequestMapping("test")
public class TestController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping("/add")
    public void add(){
        UserPojo userPojo = new UserPojo();
        userPojo.setName("小二");
        userPojo.setAge(20);
        UserPojo userPojo1 = mongoTemplate.insert(userPojo);
        System.out.println(userPojo1);
    }

    @GetMapping("/findAll")
    public void findAll(){
        List<UserPojo> all = mongoTemplate.findAll(UserPojo.class);
    }

    @GetMapping("/findwhere")
    public void findwhere(){
        Query query = new Query();
        //query.addCriteria(Criteria.where("_id").is("sdsadsadas").and("name").is("小二"));
        //mongoTemplate.findById("sdsadsadas",UserPojo.class);
        // age=20 and name=小二
        query.addCriteria(Criteria.where("age").is(20).and("name").is("小二"));
        List<UserPojo> userPojoList = mongoTemplate.find(query, UserPojo.class);
    }

    @GetMapping("/findPage")
    public void findPage(){
        Query query = new Query();
        // age=20 and name=小二
        query.addCriteria(Criteria.where("age").is(20).and("name").is("小二"));
        // 分页
        int pageNum = 1;
        int pageSize = 10;
        long count = mongoTemplate.count(query, UserPojo.class);// 查询记录数
        List<UserPojo> userPojoList = mongoTemplate.find(query.skip((pageNum - 1)*pageSize).limit(pageSize),UserPojo.class);
    }

    /**
     * mongoDB分组统计分页查询
     */
    @GetMapping("/groupByCount")
    public void groupByCount(long pageNum,long size,String code,String orderNo){
        // 假如根据 code 与 orderNo 进行查询
        Criteria criteria = Criteria.where("code").is(code).and("orderNo").is(orderNo);
        // 根据日期分组
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),// 匹配条件
                Aggregation.group("createDate") // 分组字段
                           .first("createDate").as("createDate")
                           .count().as("count1") // 统计
                           .sum("price").as("price"), // 价格求和
                Aggregation.sort(Sort.Direction.DESC,"createDate"),// 排序
                Aggregation.skip((pageNum - 1)*size),//分页
                Aggregation.limit(size)
        );
        AggregationResults<UserPojoVo> result = mongoTemplate.aggregate(aggregation, UserPojo.class, UserPojoVo.class);
        List<UserPojoVo> list = result.getMappedResults();
        System.out.println(list);
        System.out.println(result.getMappedResults().size());// total 总记录数
    }

    /**
     * 多表查询
     * @param pageNum
     * @param pageSize
     * @param userId
     */
    @GetMapping("/find/{pageNum}/{pageSize}/{userId}")
    public void test(@PathVariable long pageNum, @PathVariable long pageSize, @PathVariable String userId){
        LookupOperation lookupOperation = LookupOperation.newLookup()
                .from("t_group_member")//从表（关联的表）
                .localField("groupId")//主表中与从表相关联的字段
                .foreignField("groupId")//从表与主表相关联的字段
                .as("groups");// 结果集别名,也是从表别名
        //主表 条件
        Criteria criteria = Criteria.where("create_user").is(userId);
        // 从表条件
        criteria.andOperator(Criteria.where("groups.user_id").is(userId));// 加上别名
        //主表
        AggregationOperation match = Aggregation.match(criteria);
        SortOperation sort = Aggregation.sort(Sort.Direction.DESC, MongoUtil.fnToFieldName(GroupEntity::getUpdateTime));
        Aggregation aggregation = Aggregation.newAggregation(lookupOperation,match,sort);
        List<GroupEntity> mappedResults = MongoUtil.mongoTemplate.aggregate(aggregation, GroupEntity.class, GroupEntity.class).getMappedResults();
        System.out.println(mappedResults);
    }

    //-------------------------------------- UserRepository -----------------------------------------
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/findAll1")
    public void findAll1(){
        List<UserPojo> all = userRepository.findAll();
    }

    // 分页查询
    @GetMapping("/findPage1")
    public void findPage1(){
        Sort sort = Sort.by(Sort.Direction.DESC, "_id");
        int pageNum = 1;
        PageRequest pageRequest = PageRequest.of(pageNum - 1, 10,sort);// 默认 0页开始

        UserPojo userPojo = new UserPojo();
        userPojo.setAge(20);
        userPojo.setName("小");
        Example<UserPojo> userPojoExample = Example.of(userPojo);

        Page<UserPojo> all = userRepository.findAll(userPojoExample,pageRequest);
    }

    // 模糊查询
    @GetMapping("/findLike1")
    public void findLike1(){
        // 设置模糊匹配规则
        ExampleMatcher matching = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)// 字符串匹配
                .withIgnoreCase(true);// 忽略大小写

        UserPojo userPojo = new UserPojo();
        userPojo.setAge(20);
        userPojo.setName("小");
        Example<UserPojo> userPojoExample = Example.of(userPojo,matching);
        List<UserPojo> all = userRepository.findAll(userPojoExample);
    }
}
